What is AJAX?
AJAX is not a programming language.
AJAX just uses a combination of:
- A browser built-in XMLHttpRequest object (to request data from a web server)
- JavaScript and HTML DOM (to display or use the data)
AJAX 可以实现异步通信
How AJAX Works
How to use AJAX
The keystone of AJAX is the XMLHttpRequest object.
creating an XMLHttpRequest object
1 | var xhttp = new XMLHttpRequest(); |
send a request to a server, we use the open()
and send()
methods of the XMLHttpRequest
object
1 | xhttp.open("GET", "ajax_info.txt", true); |
GET or POST?
GET is simpler and faster than POST, and can be used in most cases.
However, always use POST requests when:
- A cached file is not an option (update a file or database on the server).
- Sending a large amount of data to the server (POST has no size limitations).
- Sending user input (which can contain unknown characters), POST is more robust and secure than GET.
Project
demo of our web applications: http://34.211.21.63/Event/
Complete HTML/CSS/Javascript code
http://jsbin.com/hocukukiva/edit?html,css,js
将JSBin里面的代码分别放在:1
2
3/WebContent/index.html
/WebContent/styles/main.css
/WebContent/scripts/main.js
访问: http://localhost:8080/Jupiter
自动跳转至index.html
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset
1 | font-size: 0.9em; |
JavaScript
Step 1 ()() Run the scripts
1 | // Run all following scripts |
Step 2 Gloval Variables
1 | var user_id = '1111'; |
step3: main function(entrance)
1 | init(); |
step5: create $ function
1 | /** |
step6: create AJAX helper function
1 | /** |
step 7: initGeoLocation function
1 | function initGeoLocation() { |
step 8: onPositionUpdated function
1 | function onPositionUpdated(position) { |
step 9: onLoadPositionFailed function
1 | function onLoadPositionFailed() { |
step 10: getLocationFromIP function
1 | function getLocationFromIP() { |
step 11: loadNearbyItems function
1 | /** |
step 12: activeBtn function
1 | /** |
step 13: showLoadingMessage function
1 | function showLoadingMessage(msg) { |
step16: listItems function
1 | /** |
step17: addItem function
1 | /** |